package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 根据vids查询小视频列表
     *
     * @param vids
     * @return
     */
    /*@Override
    public List<Video> findMovementByvids(List<Long> vids) {

        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query, Video.class);
    }*/

    /**
     * 分页查询小视频数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<Video> queryVideoList(Integer page, Integer pageSize) {

        Query query = new Query().limit(pageSize).skip((page - 1) * pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }

    //保存视频信息到MongoDB
    @Override
    public String save(Video video) {
        //1.设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2.调用方法,保存对象
        mongoTemplate.save(video);

        return video.getId().toString();
    }

    //查询指定id发布的视频
    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long uid) {
        //1.先查询id 的所有视频数量
        Query query = Query.query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query, Video.class);

        //2.查询分页数据
        query.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);

        //3.构造返回值
        PageResult result = new PageResult(page, pagesize, count, list);
        return result;
    }
}
